<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;" v-loading.fullscreen.lock="fullscreenLoading">
			<el-row>
				<el-input style="width:247px">
					<template slot="prepend">
						<span>商品状态</span>
					</template>
					<el-select v-model="onlineStatus" slot="prefix" style="width:150px;margin-left:-5px" @change="search">
						<el-option label="全部" :value="-1"></el-option>
						<el-option label="上架的商品" :value="1"></el-option>
						<el-option label="下架的商品" :value="0"></el-option>
					</el-select>
				</el-input>
			</el-row>
			<el-row style="margin-top:20px" v-if="$store.getters.getRoleTpye === 'admin' ||handelUpdateRole(17)">
				<el-button type="primary" size="small" plain @click="handleOffline(true)" v-if="onlineStatus!=1" :disabled="keyIds.length==0">
					上架商品
				</el-button>
				<el-button type="primary" size="small" plain @click="handleOffline(false)" v-if="onlineStatus!=0" :disabled="keyIds.length==0">
					批量下架
				</el-button>
				<el-button type="danger" size="small" plain :disabled="keyIds.length==0" @click="batchDelete">批量删除</el-button>
				<button  class="upl" style="margin-right: 10px;">
					Excel导入
					<input  type="file" @change="uploadExcel($event)"  multiple="multiple" />
				</button>
				<el-button type="primary" size="small" plain @click="handlxport" :disabled="keyIds.length==0">批量导出</el-button>
				<button  class="upl" >
					上传封面
					<input  type="file" @change="uploadImg($event,'cover')" multiple="multiple" />
				</button>
				<button  class="upl" style="cursor: pointer;margin-right: 10px;">
					上传详情
					<input  type="file" @change="uploadImg($event,'detail')" multiple="multiple" style="cursor: pointer;"/>
				</button>
				<a href="product.xlsx" download="product.xlsx" style="text-decoration: none;color:#1973bf;">下载导入模板</a>
			</el-row>
		</el-col>
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;display: flex;margin-top: 10px;">
			<el-input v-model="keyword" placeholder="商品名/商品编码" style="width:200px; margin-right: 10px;"></el-input>
			<el-button type="primary" @click="search">搜索</el-button>
		</el-col>
		<el-dialog :visible.sync="viewBig" width="500px">
			<img :src="bigIcon" style="width:500px;margin:-55px -20px -40px" />
		</el-dialog>

		<!--列表-->
		<el-table :data="goodsData" highlight-current-row @selection-change="setKeyIds" ref="multipleTable" style="width: 120%;">
			<el-table-column type="selection" width="55"></el-table-column>
			<el-table-column prop="logo_url" label="商品图片" width="160">
				<template scope="scope">
					<el-button type="text" @click="viewBigIcon(scope.row.logoUrl)">
						<img :src="scope.row.logoUrl" style="width:40px;height:40px;margin:-15px 0px" />
					</el-button>
				</template>
			</el-table-column>
			<el-table-column prop="goodsName" label="商品名" sortable></el-table-column>
			<el-table-column label="商品编码" sortable>
				<template scope="scope">
					<span>{{scope.row.goodsModelNumber}}</span>
				</template>
			</el-table-column>
			<el-table-column label="市场价" min-width="100" sortable>
				<template scope="scope">
					<span>{{scope.row.marketPrice}}{{scope.row.taxStatus?'(含税)':''}}</span>
				</template>

			</el-table-column>
			<el-table-column label="商品状态" min-width="100" sortable>
				<template scope="scope">
					<span>{{scope.row.onlineStatus?'已上架':'已下架'}}</span>
				</template>
			</el-table-column>

			<el-table-column label="操作" width="350">
				<template scope="scope">
					<el-button 
						size="mini" 
						@click="doEdit(scope.row)" 
						type="info" 
						plain 
						v-if="$store.getters.getRoleTpye === 'admin' ||handelUpdateRole(15)">
						编辑
					</el-button>
					<el-button 
						size="mini" 
						type="danger" 
						@click="handleDelete(scope.$index, scope.row)" 
						plain 
						v-if="$store.getters.getRoleTpye === 'admin' ||handelUpdateRole(16)">
						删除
					</el-button>
				</template>
			</el-table-column>
		</el-table>
		<div class="block" align="right">
			<br>
			<el-pagination 
				:page-size="10"
				:current-page.sync="pageIndex" 
				@current-change="handleCurrentChange" 
				layout=" prev, pager, next" 
				:total="count">
			</el-pagination>
		</div>
		<!--编辑界面-->
		<!--
        	作者：1433469126@qq.com
        	时间：2018-05-17
        	描述：下载
        	v-if="exUrl"
        -->
        <div class="fil-box" v-if="exUrl">
        	<div class="dowdBox" >
	        	<span class="dowdBox-title">导出数据完成</span>
	        	<a v-bind:href="exUrl"  download="product.csv" @click="hideXxUrl">点击下载</a>
	        	<span class="close-box" @click="hideXxUrl">点击关闭</span>
	        </div>
        </div>
        
	</section>
</template>

<script>
	import * as Api from "@/api/Api.js";
	import * as Config from "@/api/Config.js";

	export default {
		data() {
			return {
				count: 0,
				viewBig: false,
				bigIcon: "",
				onlineStatus: 1,
				pageSize: 20,
				total: 100,
				currentPage: 0,
				options: [],
				searchForm: {
					name: "",
					code: "",
					catId: "",
					beginDate: "",
					endDate: "",
					catIdList: []
				},
				keyword:'',
				keyIds: [],
				goodsData: [],
				total: 0,
				page: 1,
				listLoading: false,
				sels: [], 				// 列表选中列
				editFormVisible: false, // 编辑界面是否显示
				editLoading: false,
				exUrl:'',
				editFormRules: {
					name: [{
						required: true,
						message: "请输入姓名",
						trigger: "blur"
					}]
				},
				pageIndex: 1,
				fullscreenLoading: false
			};
		},

		methods: {
			
			search() {
				
				this.pageIndex =  1
				this.doQuery()
			},
			 openFullScreen() {
		 		this.fullscreenLoading = true;
		        setTimeout(() => {
		          this.fullscreenLoading = false;
		        }, 2000);
		    },
			// Excel导入
			uploadExcel(e){
				let _this = this
			    let fs = e.target.files[0]
			    if(fs.name.indexOf('xlsx') != -1 ||fs.name.indexOf('xls') != -1){
			    	console.log(333)
			    	_this.fullscreenLoading = true;
			    	var formData = new FormData()
				    formData.append('file',fs)
				    formData.append('token',this.$store.getters.getToken)                 
					formData.append('files',event.target.files[0])
					formData.append('merchantUserId', this.$store.getters.getModel.merchantUserId)
					Api.uploadExcel(formData).then(res => {
						console.log(res)
						_this.$message("导入成功");
						_this.fullscreenLoading = false;
						_this.doQuery();
					}).catch(err =>{
						_this.$message({
							message: err.message,
							type: 'error'
						})
						_this.fullscreenLoading = false
					});
			    }else{
			    	this.$message('请选择正确的文件格式')
			    }
			     e.target.value=""
			},
			hideXxUrl(){
				this.exUrl = ''
			},
			uploadImg(event,name) {
				let _this = this;
				event.preventDefault()   
				let fileLength = 0 
				console.log(event.target.files[0])
				this.fullscreenLoading = true;
				if(Object.values(event.target.files).length>0 && Object.values(event.target.files).length<=100){
					Object.values(event.target.files).forEach((item,index)=> {
						let formData = new FormData() 
						formData.append('token',this.$store.getters.getToken)                 
						formData.append('files',event.target.files[index])
						formData.append('merchantUserId', this.$store.getters.getModel.merchantUserId)
						formData.append('category', name)
						Api.uploadImg(formData).then(res => {
							fileLength++
							if(fileLength == event.target.files.length){
								_this.$message("上传成功");
								_this.fullscreenLoading = false;
							}
							
							if(res.retCode) {
								//this.doQuery();
							} else {
						
							}
						}).catch(err => {
							_this.$message({
								message: err.message,
								type: 'error'
							})
							_this.fullscreenLoading = false;
						});
					})
				}else{
					_this.$message("上传图片不能多于100张");
				}

				
			},
			viewBigIcon(url) {
				this.bigIcon = url;
				this.viewBig = true;
			},
			setKeyIds(val) {
				this.keyIds = val;
			},
			handleDelete(index, row) {
				this.$confirm("此操作将永久删除该商品, 是否继续?", "提示", {
						confirmButtonText: "确定",
						cancelButtonText: "取消",
						type: "warning"
					})
					.then(() => {
						let model = {
							goodsId: row.goodsId,
							token: this.$store.getters.getToken,
							merchantUserId: this.$store.getters.getModel.merchantUserId
						};
						Api.handleDelete(this, model).then(res => {
							if(res.retCode) {
								this.$message("删除商品成功");
								this.doQuery();
							} else {
								this.$alert("删除商品失败");
							}
						});
					})
					.catch(() => {
						this.$message({
							type: "info",
							message: "已取消删除"
						});
					});
			},
			//性别显示转换
			handleCurrentChange(val) {
				console.log(val);
				this.pageIndex = val;
				this.doQuery();
			},
			//获取用户列表

			doQuery() {
				let pageSize = 10; // 每页显示多少条记录。
				let pageIndex = this.pageIndex - 1; // 第几页.

				// limit 计算.
				// let begin = pageIndex;
				// 这里替换上面的 用于分页。

				this.$refs.multipleTable.clearSelection();
				let params = {
					onlineStatus: this.onlineStatus,
					page: pageIndex,
					pageSize: pageSize,
					keyword: this.keyword
				};
				Api.queryGoods(this, params).then(res => {
					this.goodsData = res.data.goodsList;
					this.count = res.data.page.total;
				});
			},
			
			doEdit(row) {
				console.log(row)
				let goodsId = row.goodsId;
				this.$router.push({
					name: "addgoodsmode",
					params: {
						goodsId: goodsId
					}
				});
			},
			batchDelete(){
				this.$confirm("此操作将删除已选中的商品, 是否继续?", "提示", {
					confirmButtonText: "确定",
					cancelButtonText: "取消",
					type: "warning"
				})
				.then(() => {
					let goodsIds = [];
					this.keyIds.forEach((item, index) => {
						goodsIds.push(item.goodsId);
					});
					
					Api.batchDelete({
						token: this.$store.getters.getToken,
						goodsIds: goodsIds.join(","),
						merchantUserId: this.$store.getters.getModel.merchantUserId,
					}).then(res => {
						console.log(res);
						if(res.retCode) {
							this.$message("删除商品成功");
							this.doQuery();
						} else {
							this.$message("删除商品失败");
						}
					});
				})
				.catch(() => {
					this.$message({
						type: "info",
						message: "已取消删除"
					});
				});
			},
			// 批量导出
			handlxport() {
				
				this.$confirm("此操作将已选中的商品导出, 是否继续?", "提示", {
					confirmButtonText: "确定",
					cancelButtonText: "取消",
					type: "warning"
				})
				.then(() => {
					let goodsIds = [];
					this.keyIds.forEach((item, index) => {
						goodsIds.push(item.goodsId);
					});
					
					Api.onBatchExport({
						token: this.$store.getters.getToken,
						goodsIds: goodsIds.join(","),
						merchantUserId: this.$store.getters.getModel.merchantUserId,
					}).then(res => {
						console.log(res);
						if(res.retCode) {
							this.exUrl = res.data
							//this.doQuery();
						} else {
							this.$message("导出商品失败");
						}
					});
				})
				.catch(() => {
					this.$message({
						type: "info",
						message: "已取消导出"
					});
				});
			},
			handleOffline(status) {
				let statusMessage = "";
				if(status) {
					statusMessage = "上架";
				} else {
					statusMessage = "下架";
				}
				this.$confirm("此操作将" + statusMessage + "已选中的商品, 是否继续?", "提示", {
						confirmButtonText: "确定",
						cancelButtonText: "取消",
						type: "warning"
					})
					.then(() => {
						let goodsIds = [];
						this.keyIds.forEach((item, index) => {
							goodsIds.push(item.goodsId);
						});

						Api.onLineStatusUpdate({
							token: this.$store.getters.getToken,
							goodsIds: goodsIds.join(","),
							merchantUserId: this.$store.getters.getModel.merchantUserId,
							onlineStatus: status
						}).then(res => {
							console.log(res);
							if(res.retCode) {
								this.$message(statusMessage + "商品成功");
								this.doQuery();
							} else {
								this.$message(statusMessage + "商品失败");
							}
						});
					})
					.catch(() => {
						this.$message({
							type: "info",
							message: "已取消删除"
						});
					});
			}

			//显示新增界面

			//批量删除
		},
		// 初始化数据
		mounted() {
			Api.queryCatTree(this).then(res => {
				if(res.retCode) {
					this.searchForm.catIdList = res.data;
				}
			});
			this.doQuery();
		}
	};
</script>

<style scoped>
.upl{
	width: 80px;
	height: 32px;
	outline: none;
	position: relative;
	background: #e6f2f2;
	color: teal;
    border-radius: 3px;
	line-height: 29px;	
    font-size: 12px;
    margin-left: 10px;
    border: 1px solid #99cccc;
}
.dowdBox-title{
	width: 100%;
	height: 80px;
	line-height: 80px;
	text-align: center;
}
.upl>input{
	top: 0px;
	left: 0px;
	right: 0px;
	width: 100%;
	height: 100%;
	opacity: 0;
	position: absolute;
	display: inline-block;
}
.fil-box{
	position: fixed;
    top: 0px !important;
    right: 0px !important;
    left: 0px !important;
    bottom: 0px !important;
    z-index: 100;
    background-color: rgba(0, 0, 0, 0.5);
}
.close-box{
	width: 100%;
	height: 40px;
	color: #1973bf;
	cursor: pointer;
	line-height: 40px;
	text-align: center;
}
.dowdBox{
	left: 50%;
	top: 50%;
	width: 300px;
	height: 160px;
	border-radius: 10px;
	position: fixed;
	display: flex;
	padding: 10px;
	margin-left: -150px;
	margin-top: -80px;
	flex-direction: column;
	background: #fff;
	border: 1px solid #E5E5E5;
	
}
.dowdBox>a{
	width: 100%;
	height: 40px;
	text-decoration: none;
	line-height: 40px;
	background: #007373;
	text-align: center;
	color: #fff;
	border-radius: 5px;
	display: inline-block;
}
</style>